package org.dark.fund.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class HttpLogFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) {
            doHttpFilter((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);
        }
    }

    protected void doHttpFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        JSONObject requestInformation = new JSONObject();
        JSONObject responseInformation = new JSONObject();
        requestInformation.putOpt("url", servletRequest.getRequestURI())
                .putOpt("headers", servletRequest.getHeaderNames())
                .putOpt("params", servletRequest.getParameterMap());
        log.info("start http request {}", JSONUtil.toJsonStr(requestInformation));
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            responseInformation.putOpt("status", servletResponse.getStatus())
                    .putOpt("headers", servletResponse.getHeaderNames())
                    .putOpt("contentType", servletResponse.getContentType());
            log.info("end http response {}", responseInformation);
        }
    }

}
